package org.example.servicepay.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.model.manage.bean.Result;
import org.example.model.manage.bean.vo.PendingPayVO;
import org.example.servicepay.entity.FeeItem;
import org.example.servicepay.entity.PayOrder;
import org.example.servicepay.entity.StudentFeeRecord;
import org.example.servicepay.mapper.FeeItemMapper;
import org.example.servicepay.mapper.PayOrderMapper;
import org.example.servicepay.mapper.StudentFeeRecordMapper;
import org.example.servicepay.mapper.StudentPayMapper;
import org.example.servicepay.service.StudentPayService;
import org.example.servicepay.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 学生缴费服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class StudentPayServiceImpl implements StudentPayService {

    private final StudentFeeRecordMapper studentFeeRecordMapper;
    private final FeeItemMapper feeItemMapper;
    private final PayOrderMapper payOrderMapper;
    private final StudentPayMapper studentPayMapper;
    private final ObjectMapper objectMapper;
    
    @Override
    public Result<StudentFeeListResponse> getStudentFeeList(String studentId) {
        try {
            // 查询学生的待缴费清单
            List<StudentFeeRecord> unpaidRecords = studentFeeRecordMapper.selectUnpaidWithFeeItem(studentId);
            
            // 查询学生的已缴费清单
            List<StudentFeeRecord> paidRecords = studentFeeRecordMapper.selectPaidWithFeeItem(studentId);

            // 构建响应对象
            StudentFeeListResponse response = new StudentFeeListResponse();
            response.setStudentId(studentId);
            
            // 处理待缴费项目
            List<StudentFeeListResponse.UnpaidFeeItem> unpaidFees = unpaidRecords.stream()
                    .map(this::convertToUnpaidFeeItem)
                    .collect(Collectors.toList());
            response.setUnpaidFees(unpaidFees);
            
            // 处理已缴费项目
            List<StudentFeeListResponse.PaidFeeItem> paidFees = paidRecords.stream()
                    .map(this::convertToPaidFeeItem)
                    .collect(Collectors.toList());
            response.setPaidFees(paidFees);

            // 计算统计信息
            BigDecimal totalUnpaidAmount = unpaidFees.stream()
                    .map(StudentFeeListResponse.UnpaidFeeItem::getFeeAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            response.setTotalUnpaidAmount(totalUnpaidAmount);

            BigDecimal totalPaidAmount = paidFees.stream()
                    .map(StudentFeeListResponse.PaidFeeItem::getPayAmount)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            response.setTotalPaidAmount(totalPaidAmount);

            response.setUnpaidCount(unpaidFees.size());
            response.setPaidCount(paidFees.size());

            return Result.success(response);

        } catch (Exception e) {
            log.error("获取学生缴费清单失败：{}", e.getMessage(), e);
            return Result.error(10053, "获取缴费清单失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<PaymentResponse> batchPayFees(String studentId, StudentBatchPayRequest request) {
        return Result.error(10099, "该功能暂未实现");
    }

    @Override
    public Result<PaymentResponse> queryPaymentResult(String studentId, String outTradeNo) {
        return Result.error(10099, "该功能暂未实现");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> closePaymentOrder(String studentId, String outTradeNo) {
        return Result.error(10099, "该功能暂未实现");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handlePaymentNotify(HttpServletRequest request) {
        // 移除了微信支付回调处理逻辑
        return false;
    }

    @Override
    public Result<PaymentResponse> applyRefund(String studentId, String outTradeNo, String refundReason) {
        return Result.error(10099, "该功能暂未实现");
    }

    @Override
    public Result<Object> getPaymentHistory(String studentId) {
        return Result.error(10099, "该功能暂未实现");
    }

    @Override
    public Result<List<org.example.model.manage.bean.vo.PendingPayVO>> getPendingPayments(String studentId) {
        try {
            List<PendingPayVO> pendingPayments =
                studentPayMapper.selectPendingPaysByStudentId(studentId);
            
            return Result.success(pendingPayments);
        } catch (Exception e) {
            log.error("查询待支付项目失败：{}", e.getMessage(), e);
            return Result.error(10068, "查询待支付项目失败：" + e.getMessage());
        }
    }

    // ==================== 私有辅助方法 ====================

    private StudentFeeListResponse.UnpaidFeeItem convertToUnpaidFeeItem(StudentFeeRecord record) {
        StudentFeeListResponse.UnpaidFeeItem item = new StudentFeeListResponse.UnpaidFeeItem();
        item.setRecordId(record.getId());
        item.setFeeItemId(record.getPayId());
        
        // FeeItem feeItem = record.getFeeItem(); // 这个字段在新的StudentFeeRecord中不存在
        // 如果需要获取FeeItem信息，应该通过payId查询
        
        // 暂时使用默认值，后续可以优化
        item.setFeeName("缴费项目");
        item.setFeeAmount(BigDecimal.ZERO);
        item.setFeeDescription("缴费项目描述");
        
        return item;
    }

    private StudentFeeListResponse.PaidFeeItem convertToPaidFeeItem(StudentFeeRecord record) {
        StudentFeeListResponse.PaidFeeItem item = new StudentFeeListResponse.PaidFeeItem();
        item.setRecordId(record.getId());
        item.setFeeItemId(record.getPayId());
        item.setPayAmount(BigDecimal.ZERO); // 暂时使用默认值
        item.setPayTime(LocalDateTime.now()); // 使用当前时间作为示例
        
        // FeeItem feeItem = record.getFeeItem(); // 这个字段在新的StudentFeeRecord中不存在
        // 如果需要获取FeeItem信息，应该通过payId查询
        
        // 暂时使用默认值，后续可以优化
        item.setFeeName("缴费项目");
        item.setFeeAmount(BigDecimal.ZERO);
        
        // 查询支付订单号
        if (record.getId() != null) {
            PayOrder payOrder = payOrderMapper.selectById(record.getId());
            if (payOrder != null) {
                item.setOutTradeNo(String.valueOf(payOrder.getId()));
            }
        }
        
        return item;
    }
}